package com.shuai.robot.mq;

import com.rabbitmq.client.Channel;
import com.shuai.common.dto.ChartUpdateDTO;
import com.shuai.common.service.analysis.InnerAnalysisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;


@Component
@Slf4j
public class ErrorMsgListener {

    @DubboReference
    private InnerAnalysisService innerAnalysisService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "xs.AI.station.error.queue"),
            exchange = @Exchange(name = "xs.AI.station.error.exchange"),
            key = {"error.chart.analysis"}
    ))
    public void handleErrorMsg(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliverTag) throws IOException {
        // 这里监听的是error.queue队列中的消息
        log.error("图表id：{}分析失败", message);
        // 更新图表的状态
        ChartUpdateDTO chartUpdateDTO = ChartUpdateDTO.builder()
                .id(Long.parseLong(message))
                .errorLog("图表生成失败，人工介入中").build();
        innerAnalysisService.updateChartInfo(chartUpdateDTO);
        // TODO: 完善处理失败的消息的后续处理措施
        channel.basicAck(deliverTag, false);
    }
}
